<template>
    <div class="category-list-view">
        <Card>
            <p slot="title">分类列表</p>
            <span slot="extra">
                <Button icon="up" type="warning" @click.prevent="handleListBack">返回上级分类</Button>
                <Button icon="loop" type="primary" @click.prevent="getData(currentPid)">刷新列表</Button>
                <Button icon="plus" type="success" @click.prevent="showAddModel">添加分类</Button>
            </span>
            <Row>
                <Col>
                    <Table border="true" :loading="loading" stripe="true" :context="self" :columns="columns" :data="data"></Table>
                </Col>
            </Row>
            <Row style="padding: 5px 0">
                <Col>
                <Page ref="Page"
                      :total="page.total"
                      :size="page.size"
                      @on-change="handleChangePage"
                      @on-page-size-change="handleChangePageSize"
                      :page-size-opts="page.sizes" show-sizer show-elevator></Page>
                </Col>
            </Row>
        </Card>

        <Modal ref="editModel" v-model="editModel">
            <p slot="header" style="color:#f60;text-align:center">
                <span>修改分类信息</span>
            </p>
            <div style="text-align:center">
                <editForm :category.sync="editRow" :row-index.sync="editRowIndex" :root-node="this" @on-change="handleEdited"></editForm>
            </div>
            <div slot="footer"></div>
        </Modal>


        <Modal ref="addModel" v-model="addModel" style="width: 480px;">
            <p slot="header" style="text-align:center">
                <span>添加分类信息</span>
            </p>
            <div style="text-align:center">
                <addForm :root-node="this" @on-change="handleAdded"></addForm>
            </div>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import editForm from './EditForm.vue';
    import addForm from './AddForm.vue';

    const editButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.edit(row, index)
                }
            }
        }, '修改');
    };

    const upLevelButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    const parentId = vm.parentIds.pop();
                    vm.getData(parentId);
                }
            }
        }, '返回');
    };

    const downLevelButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.parentIds.push(row.id);
                    vm.getData(row.id);
                }
            }
        }, '下级分类');
    };


    const toggleStatusButton = (vm, h, row, index) => {
        return h('Poptip', {
            props: {
                confirm: true,
                title: '您确定要修改分类状态吗?',
                transfer: true
            },
            on: {
                'on-ok': () => {
                    vm.updateStatus(row, index);
                }
            }
        }, [
            h('a', {
                style: {
                    margin: '5px',
                    color: row.status ? 'red' : 'green'
                }
            }, row.status ? '禁用' : '启用')
        ]);
    };

    export default {
        components: {
            editForm,
            addForm
        },

        data () {
            return {
                self: this,
                loading: false,
                editModel: false,
                editRow: {},
                editRowIndex: '',
                addModel: false,
                parentIds: [0],
                currentPid: 0,
                page: {
                    total: 0,
                    current: 1,
                    size: 10,
                    sizes: [10, 30, 50, 100],
                },
                columns: [
                    {
                        title: '分类ID',
                        key: 'id',
                        width: 80
                    },
                    {
                        title: '名称',
                        key: 'name',
                    },
                    {
                        title: '添加时间',
                        key: 'created_at'
                    },
                    {
                        title: '更新时间',
                        key: 'updated_at',
                    },
                    {
                        title: '状态',
                        key: 'status',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center'
                    }
                ],
                data: []
            }
        },

        created () {
            this.init();
        },

        mounted () {
            this.getData();
        },

        watch: {
            'page': (page) => {
                this.$refs.Page.total = page.total;
                this.$refs.Page.current = page.current;
            }
        },

        methods: {
            init () {
                let vm = this;

                this.columns.forEach(item => {
                    if (item.key == 'action') {
                        item.render = (h, param) => {
                            return [
                                editButton(vm, h, param.row, param.index),
                                toggleStatusButton(vm, h, param.row, param.index),
                                downLevelButton(vm, h, param.row, param.index)
                            ]
                        };
                    }

                    if (item.key == 'status') {
                        item.render = (h, param) => {
                            if (param.row.status == true) {
                                return h('span', {
                                    style: {
                                        color: 'green'
                                    }
                                }, '已启用');
                            } else {
                                return h('span', {
                                    style: {
                                        color: 'red'
                                    }
                                }, '已禁用');
                            }
                        };
                    }
                });
            },

            getData (parentId = 0) {
                this.loading = true;
                this.currentPid = parentId;
                util.api().get(`/admin/api/categories/${parentId}?page=${this.page.current}`, {
                    headers: {
                        pageSize: this.page.size,
                    }
                }).then((resp) => {
                    if (resp.data.status == true) {
                        this.data = resp.data.data;
                        this.page.total = resp.data.meta.total;
                        this.page.current = resp.data.meta.current_page;
                        if (resp.data.data.length <= 0) {
                            this.parentIds.pop();
                        }
                    } else {
                        this.parentIds.pop();
                        this.$Message.error(resp.data.message);
                    }
                    this.loading = false;
                }).catch((e) => {
                    if (e.response) {
                        this.$Notice.error({ title: '网络请求异常', desc: e.response.data.message});
                    } else {
                        this.$Message.error('网络请求错误');
                    }
                    this.loading = false;
                });
            },

            handleListBack () {
                const parentId = this.parentIds.pop();
                this.getData(parentId);
            },

            handleChangePage (page) {
                this.page.current = page;
                this.getData();
            },

            handleChangePageSize (size) {
                this.page.size = size;
                this.getData();
            },

            handleEdited(row, index) {
                this.getData(this.currentPid);
            },

            edit (row, index) {
                this.editModel = true;
                this.editRow = row;
                this.editRowIndex = index;
            },

            updateStatus (row, index) {
                let newStatus = !row.status;

                util.api().patch(`/admin/api/categories/${row.id}/status/${newStatus}`).then((resp) => {
                    if (resp.data.status == true) {
                        this.data[index].status = newStatus;
                        this.$Message.success(resp.data.message);
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                }).catch((e) => {
                    if (e.response) {
                        if (e.response.status == 422) {
                            if (e.response.data.hasOwnProperty('errors')) {
                                for (let i in e.response.data.errors) {
                                    this.$Notice.error({ title: '表单数据验证失败', desc: e.response.data.errors[i][0] });
                                }
                            }
                        } else {
                            this.$Message.error(e.response.data.message);
                        }
                    }  else {
                        this.$Message.error('网络请求异常');
                    }
                });
            },

            showAddModel () {
                this.addModel = true;
            },

            handleAdded(data) {
                this.getData(this.currentPid);
            },

        }
    };
</script>